<?php

namespace App\Modules\Post\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\QueryBuilder\QueryBuilder;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\AllowedInclude;
use App\Modules\Post\Models\Post;
use App\Modules\Post\Models\PostCate;
use App\Modules\Post\Resources\PostResource;
use App\Http\Controllers\Controller;

class PostController extends Controller
{

    /**
     * @var Laoha\Modules
     */
    protected $module_slug = "post";
    protected $model = false;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {  

        $this->model = new Post();

        if($request->get('_help')){
            $data = $this->help($request);
        }else{
            $data = $this->checkQuery($request);
        }        
        return json_ok($data);             
    }
    public function test(?Request $request=null)
    {
        return $request;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Modules\Post\Http\Requests\PostCreateRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = AdminUser::find($id);
        $result['data'] = (new PostResource($data))->resolve();
        $result['module'] = get_module($this->module);
        dd($result);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Modules\Post\Http\Requests\PostUpdateRequest  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    protected function checkQuery(Request $request)
    {       
//sql_start();
		$limit    = (int)$request->get('limit',0);
        $per_page = (int)$request->get('per_page',0);
        

		$allowed = [
            'filters'  => $this->model::allowedFilters(),
            'defsort'  => $this->model::listSort(),
			'sorts'    => $this->model::allowedSorts(),
			'fields'   => $this->model::allowedFields(),
            'appends'  => $this->model::allowedAppends(),
            'includes' => $this->model::allowedIncludes(),
            ];   
dd($allowed);
        $data = QueryBuilder::for($this->model->query());


        if($allowed['defsort']){
            $data = $data->defaultSort($allowed['defsort']);
        }                 
        if($allowed['sorts']){
            $data = $data->allowedSorts($allowed['sorts']);
        }
        if($allowed['filters']){
            $data = $data->allowedFilters($allowed['filters']);
        }
        if($allowed['fields']){
            $data = $data->allowedFields($allowed['fields']);
        }
        if($allowed['appends']){     
            $data = $data->allowedAppends($allowed['appends']);
        }
        if($allowed['includes']){
            $data = $data->allowedIncludes($allowed['includes']);
        }
        //未显式指定显示字段
        if(empty($request->get(config('query-builder.parameters.fields')))){
            $data = $data->select($this->model::listFields());
        }
        if(empty($allowed['includes']) || !$request->has(config('query-builder.parameters.include')) ){
            $data = $data->with($this->model::listWith());
        }   
        
        if( $limit > 0 ){
            $data = $data->simplePaginate($limit);
        }elseif($per_page > 0){
            $data = $data->paginate($per_page);
        }else{
            $data = $data->paginate();   
        }
    
        $data = $data->appends(request()->query()); 
        return $data->toArray();

//sql_end();           
    }  

    protected function help(Request $request)
    {        
        $fields	= get_table_fields((new $this->model())->getTable());
        $query	= [
			'include' => config('query-builder.parameters.include'),
			'filter'  => config('query-builder.parameters.filter'),
			'sort'    => config('query-builder.parameters.sort'),
			'fields'  => config('query-builder.parameters.fields'),
			'append'  => config('query-builder.parameters.append')
			];
		$allowed = [
			'include' => $this->model::allowedIncludes(),
			'filter'  => $this->model::allowedFilters(),
			'sort'    => $this->model::allowedSorts(),
			'fields'  => $this->model::allowedFields(),
			'append'  => $this->model::allowedAppends()
			];
		$default = [
			'with'   => $this->model::listWith(),
			'fields' => $this->model::listFields(),
			'sort'   => $this->model::listSort()
            ];
            
        
        foreach ($allowed['filter'] as $key => $value) {
            if($value instanceof AllowedFilter){
                $allowed['filter'][$value->getName()] = $value->getInternalName(); 
            }else{
                $allowed['filter'][$value]='like';
            }
            unset($allowed['filter'][$key]);
        }
        $simple = 'limit';
        $data = compact('fields','query','allowed','default','simple');
        return $data;
    }        
}
